
package mx.unam.fciencias.ppc.beansboard.comm;

import java.io.*;
import java.net.*;
import java.util.Scanner;

/**
 *
 * @author lander
 */
final class CollabServiceServerThread extends CollabService implements Runnable{

    private Socket socket;
    private CollabServiceServerMain server;
    private PrintWriter pw;
    private Scanner sc;
    private String user;
    
    public CollabServiceServerThread(Socket s, CollabServiceServerMain server) throws IOException{
        socket = s;
        this.server = server;
        pw = new PrintWriter(socket.getOutputStream());
        sc = new Scanner(socket.getInputStream());
        user = null;
    }
    
    /**
     * Message sent to the client via <code>PrintWriter</code>
     * @param message Message to be sent
     */
    protected void sendMessage(String message){
        pw.println(message);
        pw.flush();
    }
    
    /**
     * Method for sending a file to the client, we first send a message to the 
     * client telling the file we are sending and its size and then send the file
     * @param f File Requested by the client
     * @throws java.io.IOException Exception if unnable to read the file or unnable to get the <code>OutputSteam</code>
     */
    private void sendFileToClient(File f) throws IOException {
        File sf = new File(server.getPath(), f.getPath());
        FileInputStream fis = new FileInputStream(sf);
        sendMessage(sendFile(f));
        OutputStream os = socket.getOutputStream();
        int r = fis.read();
        while(r != -1){
            os.write(r);
            r = fis.read();
        }
    }
    
    public void run(){
        while(!socket.isClosed()){
            String s = sc.nextLine();
            String[] tokens = s.split(CollabService.DELIMITER);
            int c = Integer.parseInt(tokens[0]);
            switch(c){
                case LOGIN:
                    user = tokens[1];
                    server.log("The user "+user+" logged in");
                    break;
                case GETFILE:
                    try{
                    sendFileToClient(new File(tokens[1]));
                    }catch(IOException ioe){
                        server.log("An error ocurred when trying to send the file: "+tokens[2]+" to the user: "+user+"\n"+ioe.getMessage());
                    }
                    break;
                case LOGOUT:
                    server.log("The user "+tokens[1]+" logged out");
                    server.logout(this);
                    pw.flush();
                    pw.close();
                    sc.close();
                    try{
                    socket.close();
                    }catch(IOException ioe){
                        server.log("An error ocurred when trying to close the socket with user "+user+"\n"+ioe.getMessage());
                    }
                    break;
                default:
                    server.broadcast(s, this);
            }
        }
    }
}
